import dayjs from "dayjs";
import { usePublicHooks } from "../hooks";
import { reactive, ref, onMounted, h } from "vue";
import { message } from "@/utils/message";
import { addDialog } from '@/components/ReDialog'
import { ElMessageBox, ElSwitch } from 'element-plus'
import { type FormItemProps } from "./types";
import { type PaginationProps } from "@pureadmin/table";
import elForm from '../form.vue'
import { $t } from "@/plugins/i18n";
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";

import { agvList, addAgv, updateAgv, delAgv, UpdateStatus, agvModels, vehicletypes, agvBrand } from '@/utils/api/dispatch/agv'
import { GetAllMap } from '@/utils/api/dispatch/map'
import { GetAllStation } from '@/utils/api/dispatch/station'

export function useDept() {
    const { locale } = useTranslationLang(); // 获取语言
    const form = reactive({
        agvname: "",
        ip: "",
        cehicletype: null,
        status: null,
        pageNumber: 0,
        pageSize: 10,
        sortName: "createtime",
        sortType: 0
    });

    const formRef = ref();
    const dataList = ref([]);
    const loading = ref(true);
    const { tagStyle } = usePublicHooks();
    const pagination = reactive<PaginationProps>({
        total: 0,
        pageSize: 10,
        currentPage: 1,
        background: true
    });
    var agvModel = ref([])
    var vehicletype = ref([])
    var mapTypes = ref([])
    var agvBrands = ref([])
    var chargingSelect = ref([])
    var stopSelect = ref([])
    // 状态
    function formatState(status) {
        const stateMap = {
            0: '禁用',
            1: '启用',
            2: '锁定',
        }
        return stateMap[status]
    }

    const columns = ref<TableColumnList>([
        {
            label: $t('agvs.vehicleName'),
            prop: "name",
            width: 120,
            align: "left",
        },
        {
            label: $t('agvs.ipAddress'),
            prop: "ip",
            width: 150,
            align: "left",
        },
        {
            label: $t('agvs.communicationPort'),
            prop: "port",
            width: 130,
            align: "left",
        },
        {
            label: $t('agvs.brand'),
            prop: "BrandName",
            width: 100,
            align: "left",
        },
        {
            label: $t('agvs.model'),
            prop: "ModelName",
            width: 80,
            align: "left"
        },
        {
            label: $t('agvs.applicableMaps'),
            prop: "MapName",
            width: 110,
            align: "left"
        },
        {
            label: $t('agvs.walkingHeight'),
            prop: "moveheight",
            width: 90,
            align: "left",
            // sortable: true
        },
        {
            label: $t('agvs.cargoWalkingHeight'),
            prop: "movelowheight",
            width: 130,
            align: "left",
            // sortable: true
        },
        {
            label: $t('agvs.sort'),
            prop: "sort",
            width: 100,
            align: "left"
        },
        {
            label: $t('agvs.status'),
            prop: "status",
            minWidth: 100,
            cellRenderer: ({ row, props }) => (
                <el-tag size={props.size} style={tagStyle.value(row.status)}>
                    {formatState(row.status)}
                </el-tag>
            )
        },
        {
            label: $t('agvs.remarks'),
            prop: "note",
            minWidth: 200,
            align: "left"
        },
        {
            label: $t('agvs.operation'),
            fixed: "right",
            width: locale.value === "zh" ? 200 : 250,
            slot: "operation"
        }
    ])

    function tableReloading() {
        columns.value = [
            {
                label: $t('agvs.vehicleName'),
                prop: "name",
                width: 120,
                align: "left",
            },
            {
                label: $t('agvs.ipAddress'),
                prop: "ip",
                width: 150,
                align: "left",
            },
            {
                label: $t('agvs.communicationPort'),
                prop: "port",
                width: 130,
                align: "left",
            },
            {
                label: $t('agvs.brand'),
                prop: "BrandName",
                width: 100,
                align: "left",
            },
            {
                label: $t('agvs.model'),
                prop: "ModelName",
                width: 80,
                align: "left"
            },
            {
                label: $t('agvs.applicableMaps'),
                prop: "MapName",
                width: 110,
                align: "left"
            },
            {
                label: $t('agvs.walkingHeight'),
                prop: "moveheight",
                width: 90,
                align: "left",
                // sortable: true
            },
            {
                label: $t('agvs.cargoWalkingHeight'),
                prop: "movelowheight",
                width: 130,
                align: "left",
                // sortable: true
            },
            {
                label: $t('agvs.sort'),
                prop: "sort",
                width: 100,
                align: "left"
            },
            {
                label: $t('agvs.status'),
                prop: "status",
                minWidth: 100,
                cellRenderer: ({ row, props }) => (
                    <el-tag size={props.size} style={tagStyle.value(row.status)}>
                        {formatState(row.status)}
                    </el-tag>
                )
            },
            {
                label: $t('agvs.remarks'),
                prop: "note",
                minWidth: 200,
                align: "left"
            },
            {
                label: $t('agvs.operation'),
                fixed: "right",
                width: locale.value === "zh" ? 200 : 250,
                slot: "operation"
            }
        ]
    }

    async function onSearch() {
        loading.value = true;
        const { Content } = await agvList(form);
        let newData = Content.Results;
        dataList.value = newData;
        pagination.total = Content.TotalCount;
        pagination.pageSize = Content.PageSize;
        pagination.currentPage = Content.PageNumber + 1;

        setTimeout(() => {
            loading.value = false;
        }, 500);
    }

    // 重置
    function resetForm(formEl) {
        if (!formEl) return;
        formEl.resetFields();
        onSearch();
    }

    function openDialog(title = "新增", row?: FormItemProps) {
        const newTitle = title === "新增" ? $t('agvs.newlyAddedVehicles') : $t('agvs.vehicleEditing')
        addDialog({
            title: newTitle,
            props: {
                formInline: {
                    id: row?.id ?? null,
                    name: row?.name ?? "",
                    ip: row?.ip ?? "",
                    port: row?.port ?? "",
                    brand: row?.brand ?? "",
                    moveheight: row?.moveheight ?? null,
                    model: row?.model ?? null,
                    movelowheight: row?.movelowheight ?? null,
                    status: row?.status ?? 1,
                    note: row?.note ?? "",
                    vehicletype: row?.vehicletype ?? null,
                    sort: row?.sort ?? null,
                    mapid: row?.mapid ?? null,
                    license: row?.license ?? "",
                    chargingpoint: (row?.chargingpoint && row?.chargingpoint?.split(',').map(Number)) ?? [],
                    stoppoint: (row?.stoppoint && row?.stoppoint?.split(',').map(Number)) ?? []
                },
                agvModel: agvModel.value || [],
                vehicletype: vehicletype.value || [],
                mapTypes: mapTypes.value || [],
                agvBrands: agvBrands.value || [],
                chargingSelect: chargingSelect.value || [],
                stopSelect: stopSelect.value || []
            },
            width: "35%",
            draggable: true,
            fullscreenIcon: true,
            closeOnClickModal: false,
            contentRenderer: () => h(elForm, { ref: formRef } as any),
            beforeSure: (done, { options }) => {
                const FormRef = formRef.value.getRef();
                const curData = options.props.formInline as FormItemProps;
                function chores() {
                    message($t('form.operationSuccessful'), {
                        type: "success"
                    });
                    done(); // 关闭弹框
                    onSearch(); // 刷新表格数据
                }
                FormRef.validate(valid => {
                    if (valid) {
                        console.log("curData", curData);
                        curData.chargingpoint = curData.chargingpoint.toString()
                        curData.stoppoint = curData.stoppoint.toString()
                        // 表单规则校验通过
                        if (title === "新增") {
                            delete curData.id
                            addAgv(curData).then(res => {
                                if (res.Code === 0) chores();
                            })
                        } else {
                            let data = Object.assign(curData, { id: row.id })
                            updateAgv(data).then(res => {
                                if (res.Code === 0) chores();
                            })
                        }
                    }
                });
            }
        })
    }

    // 删除
    function handleDelete(row) {
        // ElMessageBox({
        //   title: '提示',
        //   message: h('p', null, [
        //     h('p', null,`是否确认删除名称为${row.name}的数据项?`),
        //     h('p', { style: 'color: red' }, '会一同删除与之关联的数据！'),
        //   ]),
        // }).then(()=>{
        //   delAgv({id:row.id,deleteAll:1}).then(res => {
        //     if (res.Code === 0) {
        //       message(`您删除了名称为${row.name}的这条数据`, { type: "success" });
        //       onSearch();
        //     }
        //   })
        // }).catch(() => { })
        ElMessageBox.confirm(
            `删除${row.name}时会一同删除与其关联的数据?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            delAgv({ id: row.id, deleteAll: 1 }).then(res => {
                if (res.Code === 0) {
                    message($t('form.operationSuccessful'), { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    // 禁用/启用
    function handleStatus(row) {
        let typeName = row.status !== 1 ? $t('form.activateVehicle') : $t('form.disableVehicles')
        ElMessageBox.confirm(
            typeName,
            $t('form.prompt'),
            {
                confirmButtonText: $t('form.confirm'),
                cancelButtonText: $t('form.cancel'),
                type: 'warning',
                center: true,
            }
        ).then(() => {
            let state = row.status === 0 ? 1 : 0
            let data = { id: row.id, state }
            UpdateStatus(data).then(res => {
                if (res.Code === 0) {
                    message($t('form.operationSuccessful'), { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    function handleSizeChange(val: number) {
        form.pageSize = val
        onSearch()
    }

    function handleCurrentChange(val: number) {
        form.pageNumber = val - 1
        onSearch()
    }

    onMounted(async () => {
        let { Content: model } = await agvModels()
        agvModel.value = model
        let { Content: type } = await vehicletypes()
        vehicletype.value = type
        // 地图select
        let { Content: map } = await GetAllMap()
        mapTypes.value = map

        let { Content: brand } = await agvBrand()
        agvBrands.value = brand
        // 充电点
        let { Content: charging } = await GetAllStation({ stationType: 2 })
        chargingSelect.value = charging
        // 返航点
        let { Content: stop } = await GetAllStation({ stationType: 1 })
        stopSelect.value = stop

        onSearch()
    })

    return {
        columns,
        loading,
        dataList,
        openDialog,
        handleDelete,
        form,
        onSearch,
        resetForm,
        pagination,
        handleSizeChange,
        handleCurrentChange,
        handleStatus,
        tableReloading
    }
}